package com.threegroup.admin.utils;

import com.alibaba.fastjson.JSON;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DeliverCallback;
import com.threegroup.admin.dto.DishDTO;
import org.springframework.boot.CommandLineRunner;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
@Component//该类加入容器管理
public class RabbitMqRecive implements CommandLineRunner {

    @Resource
    private ElasticsearchRestTemplate restTemplate;
    //定义队列名称
    private final static String QUEUE_NAME = "confirm_async";



    @Override
    public void  run(String... args) throws Exception {
        //创建连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        //工厂设置
        factory.setHost("192.168.200.180");
        factory.setVirtualHost("/shop");
        factory.setUsername("shop");
        factory.setPassword("shop");
        //根据工厂创建连接
        Connection connection = factory.newConnection();
        //根据连接创建信道
        Channel channel = connection.createChannel();
        //绑定队列
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);
//        System.out.println(" [*] Waiting for messages. To exit press CTRL+C");

        DeliverCallback deliverCallback = (consumerTag, delivery) -> {
            String message = new String(delivery.getBody(), "UTF-8");
            DishDTO jsonObject = (DishDTO) JSON.parseObject(message, DishDTO.class);
            System.out.println("保存的信息为：" + jsonObject);
            if (restTemplate==null){
                System.out.println("restTemplate为空");
            }
            if (jsonObject != null ){
            DishDTO save = restTemplate.save(jsonObject);
            System.out.println("保存的信息成功" );}

        };
        /**
         * 消费队列
         * 1.队列名称
         * 2.自动确认
         * 3.收到的消息的实体类
         */
        channel.basicConsume(QUEUE_NAME, true, deliverCallback, consumerTag -> {


        });
    }
}
